# -*- coding: utf-8 -*-

import logging
import os
import subprocess
import sys
from contextlib import contextmanager

import pymysql


class MySQLConnection:
    """
    通用 MySQL 连接管理类，支持 DictCursor 和 MULTI_STATEMENTS 等选项。
    """

    def __init__(
            self,
            host,
            port,
            user,
            password,
            database,
            use_dict_cursor=False,
            enable_multi_statements=False
    ):
        self.db_config = {
            'host': host,
            'port': port,
            'user': user,
            'password': password,
            'database': database,
            'charset': 'utf8mb4',
            'autocommit': False,  # 明确关闭自动提交
        }

        # 可选：使用字典游标
        if use_dict_cursor:
            self.db_config['cursorclass'] = pymysql.cursors.DictCursor

        if enable_multi_statements:
            self.db_config['client_flag'] = pymysql.constants.CLIENT.MULTI_STATEMENTS

        self.logger = logging.getLogger(__name__)

    @contextmanager
    def get_connection(self):
        """使用 with 语句管理数据库连接"""
        conn = None
        try:
            conn = pymysql.connect(**self.db_config)
            self.logger.info("数据库连接已建立")
            try:
                yield conn
                conn.commit()
                self.logger.debug("事务已提交")
            except Exception as e:
                conn.rollback()
                self.logger.error(f"数据库操作出错，已回滚: {e}")
                raise
        except pymysql.Error as e:
            self.logger.error(f"数据库连接失败: {e}")
            # 保持原始异常类型，
            raise
        finally:
            if conn:
                conn.close()
                self.logger.info("数据库连接已关闭")


class MySQLDictCursor(MySQLConnection):
    def __init__(self, host, port, user, password, database):
        super().__init__(host, port, user, password, database, use_dict_cursor=True)


class MySQLCursor(MySQLConnection):
    def __init__(self, host, port, user, password, database):
        super().__init__(host, port, user, password, database, enable_multi_statements=True)


class SystemManager:
    """
        命令执行工具
    """

    def __init__(self):
        self.python_version = sys.version_info

    def run_command(self, cmd):
        """执行shell命令并返回结果
        设置了 check=True，这会导致任何非零退出码都会引发异常
        """
        try:
            if self.python_version >= (3, 7):
                # Python 3.7+ 可以使用 capture_output
                result = subprocess.run(cmd, shell=True, check=False,
                                        capture_output=True, text=True)
            else:
                # Python 3.6 及以下版本
                result = subprocess.run(cmd, shell=True, check=False,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        universal_newlines=True)
                # 返回一个字典，方便其他函数使用
            return result
        except subprocess.CalledProcessError as e:
            error_msg = e.stderr.decode() if isinstance(e.stderr, bytes) else e.stderr
            print(f"命令执行失败: {e}")
            if error_msg:
                print(f"错误信息: {error_msg}")
            return None

    def check_disk_usage(self):
        """检查磁盘使用情况"""
        print("=== 磁盘使用情况 ===")
        result = self.run_command("df -h")
        if result:
            print(result)

    def check_memory(self):
        """检查内存使用情况"""
        print("\n=== 内存使用情况 ===")
        result = self.run_command("free -h")
        if result:
            print(result)

    def run_all_checks(self):
        """运行所有检查"""
        print("CentOS 系统管理脚本")
        print("=" * 30)
        print(f"Python 版本: {self.python_version[0]}.{self.python_version[1]}.{self.python_version[2]}")

        self.check_disk_usage()
        self.check_memory()

        # 获取其他系统信息
        print("\n=== 系统信息 ===")
        commands = {
            "主机名": "hostname",
            "内核版本": "uname -r",
            "系统版本": "cat /etc/redhat-release || cat /etc/os-release | grep PRETTY_NAME",
            "启动时间": "uptime -s",
            "运行时间": "uptime -p"
        }

        for desc, cmd in commands.items():
            result = self.run_command(cmd)
            if result:
                print(f"{desc}: {result}")


def main():
    manager = SystemManager()
    manager.run_all_checks()


def get_config_path():
    if getattr(sys, 'frozen', False):
        # 打包后的 exe 环境
        application_path = os.path.dirname(sys.executable)
    else:
        # 开发环境（.py 脚本运行）
        application_path = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(application_path, 'config.ini')
    return config_path


def resource_path(relative_path):
    """ 获取资源文件的绝对路径（兼容 PyInstaller 打包后的情况） """
    if hasattr(sys, '_MEIPASS'):
        # 打包后，资源在 _MEIPASS 目录下
        return os.path.join(sys._MEIPASS, relative_path)
    else:
        # 未打包，使用当前工作目录
        return os.path.join(os.path.abspath("."), relative_path)


if __name__ == "__main__":
    main()
